package com.tony.demo.ui.base;

import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.puhui.lib.base.RootActivity;
import com.puhui.lib.utils.PhonePackageUtils;

/**
 * 可以判断界面上点击区域的处理
 */
public abstract class OriginalBaseActivity extends RootActivity {

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN && getCurrentFocus() != null &&
                getCurrentFocus().getWindowToken() != null) {

            View focusedView = getCurrentFocus();
            if (isShouldHideKeyboard(focusedView, event)) {
                PhonePackageUtils.hideKeyboard(this, focusedView.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     * 该方法最初只能处理当前界面只有一个EditText控件的情况
     * 所以自己增加了一个方法来处理 isClickOnEditText(MotionEvent event)
     */
    private boolean isShouldHideKeyboard(View focusedView, MotionEvent event) {
        if (isClickOnEditText(event)) {
            return false;
        }

        if (focusedView instanceof EditText) {
            int[] location = {0, 0};
            focusedView.getLocationOnScreen(location);
            int left = location[0], top = location[1],
                    bottom = top + focusedView.getHeight(), right = left + focusedView.getWidth();

            if (event.getRawX() > left && event.getRawX() < right
                    && event.getRawY() > top && event.getRawY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                focusedView.clearFocus();
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false;
    }

    /***
     * 检查是否是点击了当前Activity中的EditText
     */
    public boolean isClickOnEditText(MotionEvent event) {
        return false;
    }

    /***
     * 检查是否是点击了当前Activity中的EditText
     */
    public boolean checkClickArea(MotionEvent event, View... views) {
        int[] location = {0, 0};

        if (null != views && views.length > 0) {
            for (View view : views) {
                view.getLocationOnScreen(location);
                int left = location[0], top = location[1],
                        bottom = top + view.getHeight(), right = left + view.getWidth();
                if (event.getRawX() > left && event.getRawX() < right
                        && event.getRawY() > top && event.getRawY() < bottom) {
                    // 点击EditText的事件，忽略它。
                    return true;
                }
            }
        }
        return false;
    }
}
